package com.cf.er;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * game-server-ErWeiMa
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/7 下午 06:51
 */
@Slf4j
public class ErWeiMa {

    public File create(String content, int width, int height, String path) throws BizException {
        File file = new File(path);
        try {
            create(content, width, height, new FileOutputStream(file));
            return file;
        } catch (FileNotFoundException e) {
            log.error("创建二维码失败！", e);
            throw new BizException(EnumReturnCode.ERROR.getCode(), "创建二维码失败", e);
        }
    }

    public void create(String content, int width, int height, OutputStream out) throws BizException {
        String format = "png";
        //定义二维码的参数
        HashMap map = new HashMap();
        //设置编码
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置纠错等级
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 2);

        try {
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, format, out);
        } catch (Exception e) {
            log.error("二维码生成异常", e);
            throw new BizException(EnumReturnCode.ERROR.getCode(), "创建二维码失败", e);
        }
    }


    public String recognition(File file) throws BizException {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            BufferedImage image = ImageIO.read(file);
            //定义二维码参数
            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //获取读取二维码结果
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Result result = multiFormatReader.decode(binaryBitmap, hints);
            return result.getText();
        } catch (Exception e) {
            log.error("读取二维码失败！", e);
            throw new BizException(EnumReturnCode.ERROR.getCode(), "创建二维码失败", e);
        }
    }


}
